package com.dp.service.impl3;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.fckeditor.UploadRule;
import com.dp.pojo.JsonPage;
import com.dp.pojo.NewsTemplatefieldVo;
import com.dp.pojo.NewsVo;
import com.dp.pub.SysProperty;
import com.dp.util.BookConfig;
import com.dp.util.DataMap;
import com.dp.util.GenerateNewsHtml;
import com.dp.util.ImageScalee;
import com.dp.vo.NewsComment;
import com.dp.vo.NewsContenttitle;
import com.dp.vo.NewsNewsQuestion;
import com.dp.vo.NewsNewsQuestionPK;
import com.dp.vo.NewsQuestion;
import com.dp.vo.NewsQuestionAnswer;
import com.dp.vo.NewsQuestionAnswerPK;
import com.dp.vo.NewsResources;
import com.dp.vo.NewsTemplate;
import com.dp.vo.NewsTemplatefield;
import com.dp.vo.NewsTemplatefile;

@Service
@Transactional
public class NewsServiceImpl3 extends BaseImpl {
	private static int NEWS_TYPE = 1;
	/**
	 * 获得所有手机报内容信息总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public Integer findAllNewsEntityCount(DataMap hashMap){
		NewsVo news=(NewsVo) hashMap.get("news");
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		String isAuditlist = (String)hashMap.get("isAuditlist");
		Integer iCount = 0; 
		try {
		
			StringBuffer sqlS =new StringBuffer("select count(nc.cid) from t_contents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			sqlS.append(" and (nc.newstype = 'news' or nc.newstype='iphonewebview' ");
			if("1".equals(isAuditlist)){
				sqlS.append(" or nc.newstype='iphonewebview2' ");
			}
			sqlS.append(" ) ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%"+news.getContentName().toString().trim() + "%'");
				}
				if(news.getContentStatus()!=null&& news.getContentStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.content_status='"+news.getContentStatus().toString().trim() + "'");
				}
				if(news.getTestStatus()!=null&& news.getTestStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.test_status='"+news.getTestStatus().toString().trim() + "'");
				}
			}
			logger.info("findAllNewsEntityCount excute sql: " + sqlS.toString());
			sql=sqlS.toString();
				iCount=this.getOneInt();
		} catch (Exception e) {
			logger.error("findAllNewsEntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return iCount;
	}
	
	/**
	 * 获得所有手机报内容信息
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsVo>
	 */
	public List<NewsVo> findAllNewsEntity(DataMap hashMap, Integer firstrow,Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		NewsVo news=(NewsVo) hashMap.get("news");
		List<NewsVo> newsList = null; 
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		String isAuditlist = (String)hashMap.get("isAuditlist");
		try {
			
			StringBuffer sqlS =new StringBuffer("select tc.contentid,nc.cid,nc.contenttitle,tc.content_status,test_status,tc.user_id," +
			"nc.updatetime,tc.cause,nc.weburl from t_contents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			sqlS.append(" and (nc.newstype = 'news' or nc.newstype='iphonewebview' ");
			if("1".equals(isAuditlist)){
				sqlS.append(" or nc.newstype='iphonewebview2' ");
			}
			sqlS.append(" ) ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%" + news.getContentName().trim() + "%'");
				}
				if(news.getContentStatus()!=null&& news.getContentStatus().trim().length() > 0){
					sqlS.append(" AND tc.content_status='" + news.getContentStatus().trim() + "'");
				}
				if(news.getTestStatus()!=null&& news.getTestStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.test_status='" + news.getTestStatus().toString().trim() + "'");
				}
			}
			
			if(jpage!=null){
				if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
					sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord()+"");
				}
			}
			if(firstrow!=null&&maxrow!=null){
				sqlS.append(" limit "+firstrow+","+maxrow+"");
			}
			logger.info("findAllNewsEntity excute aaaaaaaaaaa dql: " + sqlS.toString());
			ArrayList conList = this.queryALLResultSet(sqlS.toString());
			newsList=new ArrayList<NewsVo>();
			NewsVo newsVo=null;
			SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(conList.size()>0)
			{
				for(int i=0;i<conList.size();i++)
				{
					HashMap tmp = (HashMap)conList.get(i);
					newsVo=new NewsVo();
					newsVo.setContentId((String)tmp.get("contentid"));
					newsVo.setCid(Integer.parseInt((String)tmp.get("cid")));
					newsVo.setContentName((String)tmp.get("contenttitle"));
					newsVo.setContentStatus((String)tmp.get("content_status"));
					newsVo.setTestStatus((String)tmp.get("test_status"));
					newsVo.setUserId((String)tmp.get("user_id"));
					newsVo.setLastupdatetime(fmt_temp.parse((String)tmp.get("updatetime")));
					newsVo.setCause((String)tmp.get("cause"));
					newsVo.setWeburl((String)tmp.get("weburl"));
					sql="select sum(nr.size) sizenr from news_resources nr,news_contenresource ncr"
						+" where ncr.cid="+newsVo.getCid()+"  and nr.rid=ncr.rid group by ncr.cid";
				    int size = this.getOneInt();
					if(size>0)	newsVo.setAttachSize(size/1024+" K");
					newsList.add(newsVo);
				}
			}
			
		} catch (Exception e) {
			logger.error("findAllNewsEntity fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return newsList;
	}
	
	public NewsVo getNewsByCOntentid(String contentid)
	{
		NewsVo tmp = null;
		this.sql = "SELECT n.cid,n.contentid,n.contenttitle,n.contenticon,n.contenttext,n.contentsource,n.newstype,n.contenthtml" +
				",n.contentsummary,n.allowScoring,n.allowComments,n.updatetime,t.cause" +
				" FROM NewsContenttitle n ,TContents t where t.contentid=n.contentid and n.contentid=:contentid";
		try {
			Query query = em.createQuery(sql);
			query.setParameter("contentid", contentid.trim());
			List<Object[]> ll=query.getResultList();
			SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(ll.size()>0)
			{
				tmp = new NewsVo();
				tmp.setCid((Integer)ll.get(0)[0]);
				tmp.setContentId((String)ll.get(0)[1]);
				tmp.setContentName((String)ll.get(0)[2]);
				tmp.setContenticon(ll.get(0)[3]+"");
				tmp.setContentInfo((String)ll.get(0)[4]);
				tmp.setPubCompany((String)ll.get(0)[5]);
				tmp.setContentType((String)ll.get(0)[6]);
				tmp.setContentHtml((String)ll.get(0)[7]);
				tmp.setContentSummary((String)ll.get(0)[8]);
				tmp.setAllowScoring((Integer)ll.get(0)[9]);
				tmp.setAllowComments((Integer)ll.get(0)[10]);
				tmp.setLastupdatetime(fmt_temp.parse(ll.get(0)[11].toString()));
				tmp.setCause((String)ll.get(0)[12]);
			}
		} catch (Exception e) {
			log.error(" getNewsByCOntentid fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return tmp;
	}
	
	public int getResSize(String contentid)
	{
	 sql = "SELECT sum(size) FROM news_resources nr,news_contenresource ncr,news_contenttitle nc " +
				"where nc.contentid='"+contentid+"' and ncr.cid=nc.cid and nr.rid=ncr.rid";
		try {
			log.info(" getResSize excute sql:" +sql);
			int size = this.getOneInt();
			return (size)/1024;
		} catch (Exception e) {
			log.info(" getResSize fail !!!" +e.getMessage());
			e.printStackTrace();
			return 0;
		}
	}
	
	public String addNews(NewsVo news,List<NewsResources> nrlist) throws Exception{
		String cid=null;
			sql = "insert into t_contents (contentid,user_id,content_name,content_summary,conten_info,content_type,content_updateddate,content_status," +
					"test_status,pub_company) values ('"+news.getContentId()+"','"+news.getUserId()+"','"+news.getContentName()+"','"+
					news.getContentSummary()+"','"+news.getContentInfo()+"','11',now(),'"+news.getContentStatus()+"','"+news.getTestStatus()
					+"','"+news.getPubCompany()+"')";
			em.createNativeQuery(sql).executeUpdate();
			
			String contenticon = SysProperty.getPrep("sysiconid_title");
			if(contenticon == null || contenticon.equals(""))
	        	contenticon = "1";
			NewsContenttitle contenttitle=new NewsContenttitle();
			contenttitle.setContentid(news.getContentId());
			contenttitle.setContenttitle(news.getContentName());
			contenttitle.setContenticon(Integer.parseInt(contenticon));
			contenttitle.setContentsummary(news.getContentSummary());
			contenttitle.setContenttext(news.getContentInfo());
			contenttitle.setContentsource(news.getPubCompany());
			contenttitle.setNewstype(news.getContentType());
			//contenttitle.setContenthtml(news.getContentHtml());
			contenttitle.setAllowScoring(news.getAllowScoring());
			contenttitle.setAllowComments(news.getAllowComments());
			//contenttitle.setWeburl(news.getWeburl());
			em.persist(contenttitle);
			cid=contenttitle.getCid()+"";
			contenttitle.setContenthtml(news.getContentHtml().replace("cid", cid));
			contenttitle.setWeburl(news.getWeburl().replace("cid", cid));
			em.merge(contenttitle);
			em.flush();
			String temp_sql = "insert into t_channel_contents(channel_id,contentid) values (";
			String newChSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
			String[] chIds = news.getChannelId().split(",");
			int isNeedTest = 0;
			String needtest = SysProperty.getPrep("news-needtest");
			if(needtest!=null && needtest.equals("false"))
				isNeedTest = 1;
			//栏目和内容的关系
			int channleid=0;
			for (int i = 0; i < chIds.length; i++) {
				sql=temp_sql + chIds[i] + ",'" + news.getContentId() + "')";
				em.createNativeQuery(sql).executeUpdate();
				
				sql="select channleid from news_extends_channel where channel_id='"+chIds[i].substring(1, chIds[i].length()-1)+"'";
				channleid=this.getOneInt();
				
				sql=newChSql+channleid+","+cid+",0,"+isNeedTest+",1)";
				em.createNativeQuery(sql).executeUpdate();
			}
			//新闻图片和内容的关系
			for(NewsResources newsResources:nrlist){
					sql = "insert into news_resources (name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values ('"+newsResources.getName()+"',"+
				newsResources.getResourcetype()+",'"+newsResources.getUrl()+"',"+newsResources.getSize()+",'"+newsResources.getRformat()+"'," +
					"'"+newsResources.getSpcode()+"','"+newsResources.getNewformat()+"','"+newsResources.getFullpath()+"')";
	        	em.createNativeQuery(sql).executeUpdate();
					sql = "insert into news_contenresource (rid,cid) values ((select LAST_INSERT_ID()),(select cid from news_contenttitle where contentid='"+news.getContentId()+"'))";
				em.createNativeQuery(sql).executeUpdate();
			}
			
			//处理新闻图片和更新新闻缩略图
			sql = "select nr.rid,nr.fullpath from news_resources nr,news_contenresource ncr,news_contenttitle nc" +
			" where nr.resourcetype=1 and nr.rid=ncr.rid and ncr.cid=nc.cid and nc.contentid='"+news.getContentId()+"' order by rid desc";
			Integer rid = null;
			String resfilename="";
			String previewimgflag = SysProperty.getPrep("news_previewimgflag");
			List<Object[]>lll =  em.createNativeQuery(sql).getResultList();
			if(lll.size()>0){
				rid=(Integer)lll.get(0)[0];
				resfilename=(String)lll.get(0)[1];
				
				String imageSizeStr = SysProperty.getPrep("news_imagesize");
				String imageFormat = SysProperty.getPrep("news_imageformat");
				String[] imageSizeAry = null;
				String[] imageFormatAry = null;
				if(imageSizeStr!=null && !imageSizeStr.equals(""))
					imageSizeAry = imageSizeStr.split(",");
				if(imageFormat == null || imageFormat.equals(""))
					imageFormat = "jpg";
				if(imageFormat != null && imageFormat.contains(","))
					imageFormatAry = imageFormat.split(",");
				HashMap<String,String> tmpMap = null; 
				ImageScalee ims = new ImageScalee();
				log.info(" -=-=Will be scale image file-=-= " +resfilename);
				if(previewimgflag != null && "1".equals(previewimgflag))
				{
					//处理新闻缩略图
					String fullpath = resfilename;
					String imageSizeScaleStr = SysProperty.getPrep("news_imagesizescale");
		        	String imageFormatScaleStr = SysProperty.getPrep("news_imageformatscale");
		        	if(imageFormatScaleStr == null || imageFormatScaleStr.equals(""))
		        		imageFormatScaleStr = "png";
					String[] imageSizeScaleAry = imageSizeScaleStr.split(","); 
					String[] imageFormatScaleAry = imageFormatScaleStr.split(","); 
					if(imageSizeScaleAry != null&&imageSizeScaleAry.length>0)
					{
						for(String imageSizeScale:imageSizeScaleAry)
						{
							String screenWidHei = imageSizeScale.split("@")[0];
							String picWidHei = imageSizeScale.split("@")[1];
							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
							int width = Integer.parseInt(picWidHei.split("x")[0]);
							int height = Integer.parseInt(picWidHei.split("x")[1]);
							if(imageFormatScaleAry!=null && imageFormatScaleAry.length>0)
								for(String imageFormatScale:imageFormatScaleAry)
									ims.compressPicsScale(fullpath, width, height, imageFormatScale, screenWidth, screenHeight);
						}
					}
					String scaleFullPath = fullpath.replace(".", "-p.");
					sql = "delete from news_resources where name="+rid+"";
					em.createNativeQuery(sql).executeUpdate();
					sql = "insert into news_resources (name,newformat,fullpath) values("+rid+",'"+imageFormatScaleStr+"','"+scaleFullPath+"')";
					em.createNativeQuery(sql).executeUpdate();
				}
				for(int i=0;i<lll.size();i++)
				{
					resfilename=(String)lll.get(i)[1];
					//处理新闻图片
					if(!"".equals(resfilename) && imageSizeAry != null)
					{
						for(String imageSize : imageSizeAry)
						{
							String screenWidHei = imageSize.split("@")[0];
							String picWidHei = imageSize.split("@")[1];
							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
							int width = Integer.parseInt(picWidHei.split("x")[0]);
							int height = Integer.parseInt(picWidHei.split("x")[1]);
							if(imageFormatAry != null)
								for(String imageFormatStr : imageFormatAry)
									ims.compressPics(resfilename, width, height, imageFormatStr,screenWidth,screenHeight);
							else
								ims.compressPics(resfilename, width, height, imageFormat,screenWidth,screenHeight);
						}
					}
				}
			
			}
			if(rid!=null){
				sql="select n.rid from news_resources n where n.name="+rid;
				int iconrid = getOneInt();
				if(iconrid>0){
					sql = "update news_contenttitle set contenticon="+iconrid+" where contentid='"+news.getContentId()+"'";
					em.createNativeQuery(sql).executeUpdate();
				}
	        }
		
		return cid;
	}
	
	public boolean updateNews(NewsVo news,List<String> delurlList,List<NewsResources> nrlist) throws Exception{
			// 更新contenttitle，where cid=？
			// 更新t_content where contentid=?
			ArrayList<String> sqlList = new ArrayList<String>();
			String title = news.getContentName();
			String summary=news.getContentSummary();
			Integer allowScoring=news.getAllowScoring();
			Integer allowComments=news.getAllowComments();
			String newstype = news.getContentType();
			String info = news.getContentInfo();
			String source = news.getPubCompany();
			String html = news.getContentHtml();
			String contentid = news.getContentId();
			Integer cid = news.getCid();
			String content_updateddate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			String content_status = news.getContentStatus();
			String test_status = news.getTestStatus();
			String[] chIds = news.getChannelId().split(",");
			//update t_contents
			sql = "update t_contents set content_name='"+title+"',content_summary='"+summary+"',conten_info='"+info+"',pub_company='"+source+"'," +
					"content_updateddate='"+content_updateddate+"',content_status='"+content_status+"',test_status='" +test_status+"' where "+
					"contentid='"+contentid+"'";
			em.createNativeQuery(sql).executeUpdate();
			//update news_contenttitle
			sql = "update news_contenttitle set contenttitle='"+title+"',newstype='"+newstype+"',contentsummary='"+summary+"',allow_scoring="+
			allowScoring+",allow_comments="+allowComments+",contenttext='"+info+"',contentsource='"+source+"',contenthtml='"+html+"'," +
					"updatetime=DATE_ADD(updatetime, INTERVAL 10 SECOND) where cid="+cid;
			em.createNativeQuery(sql).executeUpdate();
			//delete news_extends_channel_title
			sql = "delete from news_extends_channel_title where cid="+cid;
			em.createNativeQuery(sql).executeUpdate();
			String newChSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
			
			for (int i = 0; i < chIds.length; i++) 
			{
				sql=newChSql+"(select channleid from news_extends_channel where channel_id="+chIds[i]+"),"+cid+",0,"+test_status+",1)";
				em.createNativeQuery(sql).executeUpdate();
			}
			
			//更新新闻图片和内容的关系
			//删除老的新闻图片和内容的关系
			for(String url:delurlList){
				sql = "SELECT rid FROM news_resources WHERE url='"+url+"'";
				List<Integer> lll =em.createNativeQuery(sql).getResultList();
				if(lll != null && lll.size()>0)
				{
					for(int i=0;i<lll.size();i++)
					{
						Integer rid=lll.get(i);
						this.sql = "DELETE FROM news_contenresource WHERE rid ="+rid;
						em.createNativeQuery(sql).executeUpdate();
					}
				}
			}
			//新增新的新闻图片和内容的关系
			for(NewsResources newsResources:nrlist){
					sql = "insert into news_resources (name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values ('"+newsResources.getName()+"',"+
				newsResources.getResourcetype()+",'"+newsResources.getUrl()+"',"+newsResources.getSize()+",'"+newsResources.getRformat()+"'," +
					"'"+newsResources.getSpcode()+"','"+newsResources.getNewformat()+"','"+newsResources.getFullpath()+"')";
	        	em.createNativeQuery(sql).executeUpdate();
					sql = "insert into news_contenresource (rid,cid) values ((select LAST_INSERT_ID()),(select cid from news_contenttitle where contentid='"+news.getContentId()+"'))";
				em.createNativeQuery(sql).executeUpdate();
			}
			
			//处理新闻图片和更新新闻缩略图
			sql = "select nr.rid,nr.fullpath from news_resources nr,news_contenresource ncr,news_contenttitle nc" +
			" where nr.resourcetype=1 and nr.rid=ncr.rid and ncr.cid=nc.cid and nc.contentid='"+news.getContentId()+"' order by rid desc";
			Integer rid = null;
			String resfilename="";
			String previewimgflag = SysProperty.getPrep("news_previewimgflag");
			List<Object[]>lll =  em.createNativeQuery(sql).getResultList();
			if(lll.size()>0){
				rid=(Integer)lll.get(0)[0];
				resfilename=(String)lll.get(0)[1];
				
				String imageSizeStr = SysProperty.getPrep("news_imagesize");
				String imageFormat = SysProperty.getPrep("news_imageformat");
				String[] imageSizeAry = null;
				String[] imageFormatAry = null;
				if(imageSizeStr!=null && !imageSizeStr.equals(""))
					imageSizeAry = imageSizeStr.split(",");
				if(imageFormat == null || imageFormat.equals(""))
					imageFormat = "jpg";
				if(imageFormat != null && imageFormat.contains(","))
					imageFormatAry = imageFormat.split(",");
				HashMap<String,String> tmpMap = null; 
				ImageScalee ims = new ImageScalee();
				log.info(" -=-=Will be scale image file-=-= " +resfilename);
				if(previewimgflag != null && "1".equals(previewimgflag))
				{
					//处理新闻缩略图
					String fullpath = resfilename;
					String imageSizeScaleStr = SysProperty.getPrep("news_imagesizescale");
		        	String imageFormatScaleStr = SysProperty.getPrep("news_imageformatscale");
		        	if(imageFormatScaleStr == null || imageFormatScaleStr.equals(""))
		        		imageFormatScaleStr = "png";
					String[] imageSizeScaleAry = imageSizeScaleStr.split(","); 
					String[] imageFormatScaleAry = imageFormatScaleStr.split(","); 
					if(imageSizeScaleAry != null&&imageSizeScaleAry.length>0)
					{
						for(String imageSizeScale:imageSizeScaleAry)
						{
							String screenWidHei = imageSizeScale.split("@")[0];
							String picWidHei = imageSizeScale.split("@")[1];
							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
							int width = Integer.parseInt(picWidHei.split("x")[0]);
							int height = Integer.parseInt(picWidHei.split("x")[1]);
							if(imageFormatScaleAry!=null && imageFormatScaleAry.length>0)
								for(String imageFormatScale:imageFormatScaleAry)
									ims.compressPicsScale(fullpath, width, height, imageFormatScale, screenWidth, screenHeight);
						}
					}
					String scaleFullPath = fullpath.replace(".", "-p.");
					sql = "delete from news_resources where name="+rid+"";
					em.createNativeQuery(sql).executeUpdate();
					sql = "insert into news_resources (name,newformat,fullpath) values("+rid+",'"+imageFormatScaleStr+"','"+scaleFullPath+"')";
					em.createNativeQuery(sql).executeUpdate();
				}
				for(int i=0;i<lll.size();i++)
				{
					resfilename=(String)lll.get(i)[1];
					//处理新闻图片
					if(!"".equals(resfilename) && imageSizeAry != null)
					{
						for(String imageSize : imageSizeAry)
						{
							String screenWidHei = imageSize.split("@")[0];
							String picWidHei = imageSize.split("@")[1];
							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
							int width = Integer.parseInt(picWidHei.split("x")[0]);
							int height = Integer.parseInt(picWidHei.split("x")[1]);
							if(imageFormatAry != null)
								for(String imageFormatStr : imageFormatAry)
									ims.compressPics(resfilename, width, height, imageFormatStr,screenWidth,screenHeight);
							else
								ims.compressPics(resfilename, width, height, imageFormat,screenWidth,screenHeight);
						}
					}
				}
			
			}
			if(rid!=null){
				sql="select n.rid from news_resources n where n.name="+rid;
				int iconrid = getOneInt();
				if(iconrid>0){
					sql = "update news_contenttitle set contenticon="+iconrid+" where contentid='"+news.getContentId()+"'";
					em.createNativeQuery(sql).executeUpdate();
				}
	        }else{
	        	sql = "update news_contenttitle set contenticon='"+SysProperty.getPrep("sysiconid_title")+"' where contentid='"+news.getContentId()+"'";
	        	em.createNativeQuery(sql).executeUpdate();
	        }
		
		return true;
	}
	
	public ArrayList findResourceByNews(Integer cid)
	{
		String findSql = "SELECT nr.rid,nr.useragents,nr.name,nr.resourcetype,nr.url,nr.size,nr.rformat,nr.distributorid,nr.spcode,nr.isusebysys,nr.newformat,nr.fullpath" +
				" FROM news_resources nr,news_contenresource ncr where ncr.cid="+cid+" and ncr.rid=nr.rid ";
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			log.error(" findResourceByNews fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	public String getExistFilename(Integer cid){
		String sql = "select nr.url from news_contenresource ncr, news_resources nr where ncr.cid ="+cid+" and ncr.rid=nr.rid and nr.rformat in ('mp3','3gp','mp4','aac')";
		try {
			return this.queryOne(sql);
		} catch (Exception e) {
			log.error(" getExistFilename fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public boolean deleteNews(String contentid) {
		/*ArrayList<String> sqlList = new ArrayList<String>();
		String deleteSql = "delete from t_channel_contents where contentid ='"+contentid+"'";
		sqlList.add(deleteSql);
		deleteSql = "delete from t_contents where contentid ='"+contentid+"'";
		sqlList.add(deleteSql);
		deleteSql = "delete from news_extends_channel_title where cid =(select cid from news_contenttitle where contentid='"+contentid+"')";
		sqlList.add(deleteSql);
		deleteSql = "insert into t_resourcedelete (url,format) (select nr.fullpath,nr.newformat from news_resources nr,news_contenresource ncr " +
		"where ncr.cid=(select cid from news_contenttitle where contentid='"+contentid+"') and ncr.rid=nr.rid)";
		sqlList.add(deleteSql);	
		deleteSql = "delete from news_contenresource where cid=(select cid from news_contenttitle where contentid='"+contentid+"')";
		sqlList.add(deleteSql);
		deleteSql = "delete from news_resources where rid in (select rid from news_contenresource where cid=(select cid from news_contenttitle where contentid='"+contentid+"'))";
		sqlList.add(deleteSql);
		deleteSql = "delete from news_contenttitle where contentid='"+contentid+"'";
		sqlList.add(deleteSql);
		try {
			return this.execTransaction(sqlList);
		} catch (Exception e) {
			log.info(" deleteNews fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}*/
		
		//20111010
		sql="select cid from news_contenttitle where contentid='"+contentid+"'";
		int cid=getOneInt();
		
		sql="delete from t_channel_contents where contentid ='"+contentid+"'";
		em.createNativeQuery(sql).executeUpdate();
		
		sql="delete from t_contents where contentid ='"+contentid+"'";
		em.createNativeQuery(sql).executeUpdate();
		
		sql="delete from news_extends_channel_title where cid ="+cid;
		em.createNativeQuery(sql).executeUpdate();
		
		sql="insert into t_resourcedelete (url,format) (select nr.fullpath,nr.newformat from news_resources nr,news_contenresource ncr " +
		"where ncr.cid="+cid+" and ncr.rid=nr.rid)";
		em.createNativeQuery(sql).executeUpdate();
		
		sql="select rid from news_contenresource where cid="+cid+"";
		List<Integer> ll= em.createNativeQuery(sql).getResultList();
		
		sql="delete from news_contenresource where cid="+cid;
		em.createNativeQuery(sql).executeUpdate();
		if(ll.size()>0){
			for(int i=0;i<ll.size();i++){
				sql="delete from news_resources where rid="+ll.get(i);
				em.createNativeQuery(sql).executeUpdate();
				//删除资讯内容缩略图
				sql="delete from news_resources where name="+ll.get(i);
				em.createNativeQuery(sql).executeUpdate();
			}
		}
		
		sql="delete from news_contenttitle where cid="+cid;
		em.createNativeQuery(sql).executeUpdate();
		
		return true;
	}
	
	public boolean subAudit(NewsVo news)
	{
		String content_id_list = news.getAllChkValue();
		String[] c_id_strList=null;
		if(content_id_list!=null && !content_id_list.equals(""))
		{
		    c_id_strList=content_id_list.split(",");
        	for(String contentId:c_id_strList)
        	{
        		 sql = "update t_contents set content_status='auditing',content_updateddate=now() where contentid='"+contentId+"'";
        		 em.createNativeQuery(sql).executeUpdate();
        	}
        }
		return true;
	}
	
	/*public boolean unpassNews(NewsVo news)
	{
		String content_id_list = news.getAllChkValue();
		String[] c_id_strList=content_id_list.split(",");
    	for(String contentId:c_id_strList)
    	{
    		sql = "update t_contents set content_status='unpass',cause='"+news.getCause()+"',content_updateddate=now() where contentid="+contentId;
    		emr.createNativeQuery(sql).executeUpdate();
    		log.info(" unpassNews excute sql :" +sql);
    	}
        return true;
	}*/
	
	public boolean udpateAuditNews(NewsVo news,int unpass) throws Exception{
		String content_id_list = news.getAllChkValue();
		String[] c_id_strList=null;
		if(content_id_list!=null && !content_id_list.equals(""))
		{
			    c_id_strList=content_id_list.split(",");
	        	for(String contentId:c_id_strList)
	        	{
	        		if(unpass==1){
	        			//审核不通过
	        			sql = "update t_contents set content_status='unpass',cause='"+news.getCause()+"',content_updateddate=now() where contentid='"+contentId+"'";
	    	    		em.createNativeQuery(sql).executeUpdate();
	        		}else{
	        			sql = "update t_contents set content_status='pass',cause=null,content_updateddate=now() where contentid='"+contentId+"'";
		        		em.createNativeQuery(sql).executeUpdate();
		        		//查询内容测试状态
		        		sql="SELECT test_status FROM t_contents where contentid='"+contentId+"'";
		    			String test_status = getOneString();
		    			//如果已通过测试,则表示可用,修改news_extends_channel_title中的状态
		    			//修改前需要检查对应栏目的更新方式,0表示实时更新,发布状态为1,其他值为计时器,状态值为2
		    			if(test_status != null && test_status.equals("1"))
		    			{
		    				sql="select cid from news_contenttitle where contentid='"+contentId+"'";
		    				int cid = getOneInt();
		    				sql = "update news_extends_channel_title set contentstatus=2 where cid=" +cid;
		    				em.createNativeQuery(sql).executeUpdate();
		    				NewsVo newsvo = (NewsVo) getNewsByCOntentid(contentId);
		    				if(!"iphonewebview2".equals(newsvo.getContentType())){
		    					//todo执行生成静态网页
			    				Executor executor = Executors.newSingleThreadExecutor();
			    				Map<String, String> m=getUrl_NewformatByContentid(contentId);
			    				executor.execute(new GenerateNewsHtml(newsvo,NEWS_TYPE,m));
		    				}
		    			}
	        		}
	        		
	        	}
	    }
		return true;
			
	}
	
	public boolean disableNews(String contentIdStr)
	{
		ArrayList<String> sqlList = new ArrayList<String>();
		//是否需要测试--是否需要修改测试状态
		String needtest = SysProperty.getPrep("news-needtest");
		if(needtest!=null && needtest.equals("false"))
			sql = "update t_contents set content_status='disable' where contentid in ("+contentIdStr+")";
		else
			sql = "update t_contents set content_status='disable',test_status='0' where contentid in ("+contentIdStr+")";
		sqlList.add(sql);
		String cidstr = this.getCidListByContentid(contentIdStr);
		sql = "update news_extends_channel_title set contentstatus=3 where cid in (" + cidstr + ")";
		sqlList.add(sql);
		try {
			return execTransaction(sqlList);
		} catch (Exception e) {
			log.error(" disableNews fail !!!" +e.getMessage());
			e.printStackTrace();
			return false;
		}
	}
	
	public String getCidListByContentid(String contentIdStr)
	{
		String findSql = "SELECT cid FROM news_contenttitle where contentid in ("+contentIdStr+")";
		String result = "";
		try {
			ArrayList<DataMap> cidList = this.queryALLResultSet(findSql.toString());
			for(DataMap tmp:cidList)
			{
				String cid = (String)tmp.get("cid");
				result += cid+",";
			}
			if(!"".equals(result))
				result = result.substring(0,result.length()-1);
		} catch (Exception e) {
			logger.error(" getCidListByContentid fail !!!" +e.getMessage());
		}
		return result;
	}
	
	public ArrayList<DataMap> findSelectChannelsByCid(Integer cid)
	{
		String findSql = "select tc.channel_id,tc.service_code,tc.channel_name,tc.channel_comment,tc.function_name,tc.status,tc.ordered,tc.created_date,tc.previous_id,tc.primal_id,tc.level,tc.channel_type,tc.channel_hot_topics,tc.channel_classifying_label" +
				" from t_channels tc,news_extends_channel nec,news_extends_channel_title nect " +
				"where nect.cid="+cid+" and nect.channleid=nec.channleid and nec.channel_id=tc.channel_id";
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}

	/*public ArrayList<DataMap> findAllLastChannel(Object roleId, String userId) {
		//root
		String findSql = "select ch.* from t_channels ch WHERE 1=1 " +
				//will open
				" and status='"+BookConfig.channel_status_enable+"'" +
				" and (channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
		    		" and status='"+BookConfig.channel_status_enable+"'" +
					" and (channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}*/
	public ArrayList<DataMap> findAllLastChannel(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch WHERE 1=1 " +
				//will open
				" and (channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
					" and (channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			findSql = "select distinct  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
				" and (channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
	    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
	    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	//not use
	/*public ArrayList getChannelPlatform()
    {
    	ArrayList result = new ArrayList();
    	//1 取得所有生效的catalog对应的catalogchannelid
    	String sql = "SELECT ncc.channelid,ncp.* FROM news_catlog nc left join news_catlog_platform ncp on ncp.catlogid=nc.catlogid," +
    			"news_catlog_channel ncc where nc.isnowpublish in (1,2) and nc.catlogid=ncc.catlogid";
    	ArrayList catalogChannelidAndPlatformList = new ArrayList();
    	try {
    		catalogChannelidAndPlatformList = queryALLResultSet(sql);
    		if(catalogChannelidAndPlatformList.size()>0)
    		{
	    		for(int i=0;i<catalogChannelidAndPlatformList.size();i++)
	    		{
	    			DataMap lastChannelAndPlatform = new DataMap();
	    			HashMap hashmap = (HashMap)catalogChannelidAndPlatformList.get(i);
	    			String catalogChannelid = (String)hashmap.get("channelid");
	    			String platforminfo = InterUtil.rb.getString("src.gameplatform")+hashmap.get("mplatform")+"."+
	    			InterUtil.rb.getString("src.gamedistributor")+hashmap.get("magent")+"."+InterUtil.rb.getString("src.clientsn")+
	    			hashmap.get("mserialnum")+"."+InterUtil.rb.getString("src.languagearea")+hashmap.get("mlocale");
	    			sql = "SELECT nc.channel_id FROM news_buttons nb,news_extends_firstchannel_buttons nfb,news_contenttype nc where " +
	    					"nfb.channelid="+catalogChannelid+" and nc.newscontenttype=nb.buttoncontenttype and nfb.buttonid=nb.buttonid";
	    			ArrayList tchannelIdList = queryALLResultSet(sql);
	    			if(tchannelIdList.size()>0)
	    			{
	    				//首先要判断结果集里的channel是否最后一级
	    				for(int j=0;j<tchannelIdList.size();j++)
	    				{
	    					DataMap tmpMap = (DataMap)tchannelIdList.get(j);
	    					String tch_id = tmpMap.getMapData("channel_id");
	    					if(tch_id == null || tch_id.equals(""))
	    						continue;
	    					sql = "select function_name from t_channels where channel_id='"+tch_id+"'";
	    					String functionname = queryOne(sql);
	    					//if最后一级 放到map里 key是最后一级的id value是platforminfo
	    					if(functionname.toUpperCase().equals("LAST") || functionname.toUpperCase().equals("CHANNELSONG"))
	    						lastChannelAndPlatform.put(tch_id, platforminfo);
	    					//不是 递归查询
	    					else
	    						buildLastChannelAndPlatform(tch_id,platforminfo,lastChannelAndPlatform);
	    				}
	    			}
	    			result.add(lastChannelAndPlatform);
	    		}
    		}
		} catch (Exception e) {
			log.info(" NewsServiceImpl3 getChannelPlatform fail !!!" +e.getMessage());
			e.printStackTrace();
		}
    	return result;
    }*/
	
	public DataMap buildLastChannelMap()
    {
    	String sql = "SELECT channel_id,channel_name,function_name,previous_id FROM t_channels t";
    	HashMap<String,String> childIdAndPreiousId = new HashMap<String,String>();
    	HashMap<String,String> idAndName = new HashMap<String,String>();
    	DataMap result = new DataMap();
    	List chList = null;
    	try {
			chList = queryALLResultSet(sql);
		} catch (Exception e) {
			log.info(" NewsServiceImpl3 buildChChildIdAndPreviousIdMap fail !!!" +e.getMessage());
			e.printStackTrace();
			return null;
		}
		//首先建立两个map准备数据
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//先将id和name装入map
			idAndName.put(channel_id, chName);
			//channel如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_first) || fnName.equals(BookConfig.channel_normal))
			{
				childIdAndPreiousId.put(channel_id, previous_id);
			}
		}
		//build map,key:channleid value:previousid+name
		for(int i=0;i<chList.size();i++)
		{
			HashMap hashMap = (HashMap)chList.get(i);
			String channel_id = (String)hashMap.get("channel_id");
			String chName = (String)hashMap.get("channel_name");
			String fnName = (String)hashMap.get("function_name");
			String previous_id = (String)hashMap.get("previous_id");
			//如果是normal或者first,就装入map,key是channel_id,value是
			if(fnName.equals(BookConfig.channel_last) || fnName.equals(BookConfig.channel_song))
			{
				String previousChName = idAndName.get(previous_id);
				chName = chName+"="+previousChName;
				chName = getValue(childIdAndPreiousId,idAndName,previous_id,chName);
				//最上一级的频道名称必然是news,把news过滤掉
				chName = chName.substring(0,chName.lastIndexOf("="));
				String[] tmp = chName.split("=");
				String value = "";
				for(int j=tmp.length-1;j>=0;j--)
				{
					value=value+tmp[j]+"--";
				}
				value = value.substring(0,value.length()-2);
				result.put(channel_id, value);
			}
		}
    	return result;
    }
	
	private String getValue(HashMap<String,String> idmap,HashMap<String,String> namemap,String key,String result)
    {
    	String parentid = idmap.get(key);
    	String parentname = namemap.get(parentid);
    	if((key != null && parentid!=null)&& !parentid.equals(key))
    	{
    		result = result+"="+parentname;
    		return getValue(idmap,namemap,parentid,result);
    	}
    	else
    	{
    		return result;
    	}
    }
	
	//not use
	private void buildLastChannelAndPlatform(String tch_id,String platforminfo,DataMap lastChannelAndPlatform)
    {
    	String sql = "SELECT channel_id,function_name FROM t_channels where previous_id='"+tch_id+"'";
    	try {
			ArrayList chList = queryALLResultSet(sql);
			for(int i=0;i<chList.size();i++)
			{
				HashMap hashMap = (HashMap)chList.get(i);
				String fnName = (String)hashMap.get("function_name");
				String channel_id = (String)hashMap.get("channel_id");
				if(fnName.toUpperCase().equals("LAST") || fnName.toUpperCase().equals("CHANNELSONG"))
					lastChannelAndPlatform.put(channel_id, platforminfo);
				else
					buildLastChannelAndPlatform(channel_id,platforminfo,lastChannelAndPlatform);
			}
		} catch (Exception e) {
			log.info(" NewsServiceImpl3 buildLastChannelAndPlatform fail !!!" +e.getMessage());
			e.printStackTrace();
		}
    }

	//********************添加评论Start****************************
	public String getChannleidsByCid(Integer cid) {
		String channleids="";
		try {
		
			String sql="select group_concat(channleid) from news_extends_channel_title where cid="+cid+"";
			channleids=this.getOneString();
		} catch (Exception e) {
			logger.info("getChannleidsByCid fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return channleids;
	}
	public boolean addNewscomment(DataMap dataMap) {
		Boolean resultb=true;
		String channleids=(String)  dataMap.get("channleids");
		Integer cid=(Integer) dataMap.get("cid");
		NewsComment newsComment=(NewsComment) dataMap.get("newsComment");
		NewsComment newsComment1=null;
		try {
		
			String sql="insert into news_comment(cid,channleid,clientid,commenttext,name,commenttime,isgood,isdelete) values(?,?,?,?,?,?,?,?)";
			
		String [] as=	channleids.split(",");
//		List<Object[]> tempp=this.em.createNativeQuery(sql).getResultList();
//				for(Object[]o:tempp)
//				{
		Query	query=em.createNativeQuery(sql);
				
			for(String s:as){
					query.setParameter(1, cid);
					query.setParameter(2, Integer.parseInt(s));
					query.setParameter(3,newsComment.getClientid());
					query.setParameter(4,newsComment.getCommenttext());
					query.setParameter(5,newsComment.getName());
					query.setParameter(6, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newsComment.getCommenttime()));
					query.setParameter(7,newsComment.getIsgood());
					query.setParameter(8,newsComment.getIsdelete());
					query.executeUpdate();
			}
			
		} catch (Exception e) {
			logger.info("addNewscomment fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		}
		return resultb;
	}
	//********************添加评论End****************************

	//********************管理投票Start****************************
	public Integer findPollsCountByContentid(DataMap hashMap) {
		NewsQuestion newsQuestion=(NewsQuestion) hashMap.get("newsQuestion");
		String contentId=(String) hashMap.get("contentId");
		List<NewsQuestion> queryList=null;
		int totalcount = 0;
		try {
		StringBuffer sqlS = new StringBuffer("SELECT count(n.questionid) FROM NewsQuestion n,NewsNewsQuestion nnq WHERE 1=1 AND n.questionid=nnq.newsQuestion.questionid ");
					 sqlS.append(" AND nnq.newsContenttitle.cid=(SELECT cid FROM NewsContenttitle where contentid='"+contentId+"')");
		if (newsQuestion != null) {
			if (newsQuestion.getQuestisok() != null
					&& newsQuestion.getQuestisok().toString().trim().length() > 0) {
				sqlS.append(" AND n.questisok='" + newsQuestion.getQuestisok()
						+ "'");
			}
			if (newsQuestion.getAnswermutiselect() != null
					&& newsQuestion.getAnswermutiselect().toString().trim()
							.length() > 0) {
				sqlS.append(" AND n.answermutiselect='"
						+ newsQuestion.getAnswermutiselect() + "'");
			}
		}
		
		Query query = em.createQuery(sqlS.toString());
		totalcount = Integer.valueOf(query.getSingleResult().toString());
		} catch (Exception e) {
			logger.error("findPollsCountByContentid faild!!!"+e.getMessage());
			e.printStackTrace();
		}
		return totalcount;
	}
	
	public List<NewsQuestion> findPollsByContentid(DataMap hashMap,
			Integer firstrow, Integer maxrow) {
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		NewsQuestion newsQuestion=(NewsQuestion) hashMap.get("newsQuestion");
		String contentId=(String) hashMap.get("contentId");
		List<NewsQuestion> queryList=null;
		try {
		StringBuffer sqlS = new StringBuffer("SELECT n FROM NewsQuestion n,NewsNewsQuestion nnq WHERE 1=1 AND n.questionid=nnq.newsQuestion.questionid ");
					 sqlS.append(" AND nnq.newsContenttitle.cid=(SELECT cid FROM NewsContenttitle where contentid='"+contentId+"')");
		if (newsQuestion != null) {
			if (newsQuestion.getQuestisok() != null
					&& newsQuestion.getQuestisok().toString().trim().length() > 0) {
				sqlS.append(" AND n.questisok='" + newsQuestion.getQuestisok()
						+ "'");
			}
			if (newsQuestion.getAnswermutiselect() != null
					&& newsQuestion.getAnswermutiselect().toString().trim()
							.length() > 0) {
				sqlS.append(" AND n.answermutiselect='"
						+ newsQuestion.getAnswermutiselect() + "'");
			}
		}
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord()+"");
			}
		}
		Query query = em.createQuery(sqlS.toString());
		if (firstrow != null) {
			query.setFirstResult(firstrow);
		}
		if (maxrow != null) {
			query.setMaxResults(maxrow);
		}
		queryList= query.getResultList();
		} catch (Exception e) {
			logger.error("find polls faild!!!"+e.getMessage());
		}
		return queryList;
	}

	/**
	 * 新增投票
	 */
	public boolean addPollToNews(DataMap dataMap) {
		NewsQuestion newsQuestion=(NewsQuestion) dataMap.get("newsQuestion");
		List<NewsQuestionAnswer> nqalist=(List<NewsQuestionAnswer>) dataMap.get("nqalist");
		NewsVo news=(NewsVo) dataMap.get("news");
		String jpql = "";
		Query query = null;

		jpql = "SELECT max(n.questorder) FROM NewsQuestion n,NewsNewsQuestion nnq WHERE n.questionid=nnq.newsQuestion.questionid " +
				"AND nnq.newsQuestionPK.cid='"+news.getCid()+"'";
		query = em.createQuery(jpql);
		Integer questorder = 0;
		if (query.getSingleResult() != null) {
			questorder = Integer.parseInt(query.getSingleResult()
					.toString());
		}
		newsQuestion.setQuestorder(questorder + 1);
		
		NewsQuestion newsQuestion2 = em.merge(newsQuestion);
		// 插入投票选项
		for (NewsQuestionAnswer questionAnswer : nqalist) {
			jpql = "SELECT max(newsQuestionAnswerPK.answerid) FROM NewsQuestionAnswer";
			query = em.createQuery(jpql);
			Integer answerid = 0;
			if (query.getSingleResult() != null) {
				answerid = Integer.parseInt(query.getSingleResult()
						.toString());
			}

			questionAnswer
					.setNewsQuestionAnswerPK(new NewsQuestionAnswerPK(
							newsQuestion2.getQuestionid(), answerid + 1));
			em.merge(questionAnswer);
		}
		
		//插入手机报内容和投票的关系
        NewsNewsQuestion nnq=new NewsNewsQuestion(new NewsNewsQuestionPK(news.getCid(),newsQuestion2.getQuestionid()));
        em.merge(nnq);
        
		return true;
	}

	/**
	 * 投票选项信息
	 * @param newsQuestion
	 * @return
	 */
	public List<NewsQuestionAnswer> getNewsQuestionAnswerListByNqid(
			NewsQuestion newsQuestion) {
		List<NewsQuestionAnswer> queryList=null;
		try {
			String jpql = "SELECT n FROM NewsQuestionAnswer n WHERE newsQuestion.questionid=:questionid";
			Query query = em.createQuery(jpql);
			query.setParameter("questionid", newsQuestion.getQuestionid());
			queryList = query.getResultList();
		} catch (Exception e) {
			logger.error("find NewsQuestionAnswer faild!!!"+e.getMessage());
		}
		return queryList;
	}

	/**
	 * 修改投票
	 * 
	 * @param newsQuestion
	 * @param nqalist
	 * @return
	 */
	public boolean updatePollsByContentid(DataMap hashMap) {
		NewsQuestion newsQuestion=(NewsQuestion) hashMap.get("newsQuestion");
		List<NewsQuestionAnswer> nqalist=(List<NewsQuestionAnswer>) hashMap.get("nqalist");
		String jpql = "";
		Query query = null;
		
		NewsQuestion newsQuestion2 = em.merge(newsQuestion);
		// 删除原有选项
		jpql = "DELETE FROM NewsQuestionAnswer WHERE newsQuestion.questionid='"
				+ newsQuestion2.getQuestionid() + "'";
		query = em.createQuery(jpql);
		Object obj = query.executeUpdate();
		em.flush();
		em.clear();

		// 插入投票选项
		for (NewsQuestionAnswer questionAnswer : nqalist) {
			jpql = "SELECT max(newsQuestionAnswerPK.answerid) FROM NewsQuestionAnswer";
			query = em.createQuery(jpql);
			Integer answerid = 0;
			if (query.getSingleResult() != null) {
				answerid = Integer.parseInt(query.getSingleResult()
						.toString());
			}
			questionAnswer
					.setNewsQuestionAnswerPK(new NewsQuestionAnswerPK(
							newsQuestion2.getQuestionid(), answerid + 1));
			em.merge(questionAnswer);
		}
		return true;
	}

	/**
	 * 手机报内容投票排序
	 * 
	 * @param gvalue
	 * @return
	 */
	public boolean pollsortItems(DataMap hashMap,
			String gvalue) {
		NewsQuestion newsQuestion2=(NewsQuestion) hashMap.get("newsQuestion2");
		String contentId=(String) hashMap.get("contentId");
		String jpql = "";
		Query query = null;
		String[] gArys = gvalue.split("\\|");

		// 手机报内容下所有排序号清空
		jpql = "SELECT nnq FROM NewsQuestion n,NewsNewsQuestion nnq WHERE n.questionid=nnq.newsQuestion.questionid AND nnq.newsQuestionPK.cid=(SELECT cid FROM NewsContenttitle where contentid='"+contentId+"') ";
		query = em.createQuery(jpql);
		List<NewsNewsQuestion> queryList=query.getResultList();
		for(NewsNewsQuestion nnq:queryList){
			jpql = "UPDATE NewsQuestion n SET n.questorder=null WHERE n.questionid='"+nnq.getNewsQuestionPK().getQid()+"'";
			query = em.createQuery(jpql);
			query.executeUpdate();
		}
		int questorder = 1;
		for (int i = gArys.length - 1; i >= 0; i--) {
			//System.out.println(questorder+"    "+Integer.parseInt(gArys[i]));
			jpql = "UPDATE NewsQuestion n SET n.questorder=? WHERE n.questionid=?";
			query = em.createQuery(jpql);
			query.setParameter(1, questorder);
			query.setParameter(2, Integer.parseInt(gArys[i]));
			query.executeUpdate();
			questorder++;
		}

		// 排序过程中，防止有人进行了投票主题相关操作，而导致没有排序
		jpql = "SELECT n FROM NewsQuestion n,NewsNewsQuestion nnq WHERE  n.questorder is null " +
				"AND n.questionid=nnq.newsQuestion.questionid " +
				"AND nnq.newsQuestionPK.cid=(SELECT cid FROM NewsContenttitle where contentid='"+contentId+"')";
		query = em.createQuery(jpql);
		List<NewsQuestion> nqlist = query.getResultList();
		if (nqlist.size() > 0) {
			for (NewsQuestion newsQuestion : nqlist) {
				newsQuestion.setQuestorder(questorder);
				questorder++;
			}
		}
		
		return true;
	}

	/**
	 * 详情 专用
	 * @param newsQuestion
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<NewsQuestionAnswer> getNewsQuestionAnswerListByNqid2(
			NewsQuestion newsQuestion) {
		List<NewsQuestionAnswer> nqalist=new ArrayList<NewsQuestionAnswer>();
		try {
		String jpql = "SELECT n FROM NewsQuestionAnswer n WHERE newsQuestion.questionid=:questionid";
		Query query = em.createQuery(jpql);
		query.setParameter("questionid", newsQuestion.getQuestionid());
		List<NewsQuestionAnswer> queryList = query.getResultList();
		int Totalanswerpoint=0;
		for(NewsQuestionAnswer questionAnswer:queryList){
			Totalanswerpoint+=questionAnswer.getAnswerpoint();
		}
		
		for(NewsQuestionAnswer questionAnswer:queryList){
			questionAnswer.setAnswernum(questionAnswer.getAnswerpoint()+"("+percent(questionAnswer.getAnswerpoint(),Totalanswerpoint)+")");
			double d=(questionAnswer.getAnswerpoint()/(double)Totalanswerpoint)*200;
			questionAnswer.setAnswerpoint((int)d);
			//System.out.println("百分比:"+percent(questionAnswer.getAnswerpoint(),Totalanswerpoint));
			//System.out.println("宽度："+questionAnswer.getAnswerpoint());
			nqalist.add(questionAnswer);
		}
		
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return nqalist;
	}
	/**
	 * 计算百分比
	 * @param p1
	 * @param p2
	 * @return
	 */
	private  String percent(double p1,double p2){
		  String str;
		  double p3=0;
		  if(p2!=0){
			  p3=p1/p2;
		  }
		  NumberFormat nf=NumberFormat.getPercentInstance();
		  if(p1==0){
			  nf.setMinimumFractionDigits(0);
		  }else{
			  nf.setMinimumFractionDigits(2);
		  }
		  str=nf.format(p3);
		  return str;
	}
	//********************管理投票End****************************

	public boolean generated_html(String contentIdStr) {
		String[] idArray = contentIdStr.split(",");
		for(String contentId:idArray){
			//todo执行生成静态网页
			NewsVo newsvo = this.getNewsByCOntentid(contentId);
			Executor executor = Executors.newSingleThreadExecutor();
			Map<String, String> m=getUrl_NewformatByContentid(contentId);
			executor.execute(new GenerateNewsHtml(newsvo,NEWS_TYPE,m));
		}
		return true;
	}
	
	//得到内容的url-newformatMap映射，处理base64图片时候用
	public Map<String, String> getUrl_NewformatByContentid(String contentId) {
		 sql="select nr.url,nr.newformat from news_resources nr,news_contenresource ncr,news_contenttitle nc where nr.rid=ncr.rid and ncr.cid=nc.cid and nc.contentid=:contentId";
		 Map<String, String> m=new HashMap<String, String>();
		 List<Object[]> ll=em.createNativeQuery(sql).setParameter("contentId", contentId).getResultList();
		 if(ll.size()>0){
			 for(int i=0;i<ll.size();i++){
				 m.put((String)ll.get(i)[0], (String)ll.get(i)[1]);
			 }
		 }
     	 return m;                                      
	}
	
	/*==============================================================*/
	/* Webview内容管理Start                                         
	/*==============================================================*/
	/**
	 * 获得所有Webview内容总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public Integer findAllNews2EntityCount(DataMap hashMap){
		NewsVo news=(NewsVo) hashMap.get("news");
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		Integer iCount = 0; 
		try {
			
			StringBuffer sqlS =new StringBuffer("select count(nc.cid) from t_contents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			sqlS.append(" and nc.newstype='iphonewebview2' ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%"+news.getContentName().toString().trim() + "%'");
				}
				if(news.getContentStatus()!=null&& news.getContentStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.content_status='"+news.getContentStatus().toString().trim() + "'");
				}
				if(news.getTestStatus()!=null&& news.getTestStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.test_status='"+news.getTestStatus().toString().trim() + "'");
				}
			}
			logger.info("findAllNews2EntityCount excute sql: " + sqlS.toString());
			sql=sqlS.toString();
				iCount=this.getOneInt();
			
		} catch (Exception e) {
			logger.error("findAllNews2EntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return iCount;
	}
	
	/**
	 * 获得所有Webview内容信息
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsVo>
	 */
	public List<NewsVo> findAllNews2Entity(DataMap hashMap, Integer firstrow,Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		NewsVo news=(NewsVo) hashMap.get("news");
		List<NewsVo> newsList = null; 
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		try {
		
			StringBuffer sqlS =new StringBuffer("select tc.contentid,nc.cid,nc.contenttitle,tc.content_status,test_status,tc.user_id," +
			"nc.updatetime,tc.cause,nc.weburl from t_contents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			sqlS.append(" and nc.newstype='iphonewebview2' ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%" + news.getContentName().toString().trim() + "%'");
				}
				if(news.getContentStatus()!=null&& news.getContentStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.content_status='" + news.getContentStatus().toString().trim() + "'");
				}
				if(news.getTestStatus()!=null&& news.getTestStatus().toString().trim().length() > 0){
					sqlS.append(" AND tc.test_status='" + news.getTestStatus().toString().trim() + "'");
				}
			}
			
			if(jpage!=null){
				if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
					sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord()+"");
				}
			}
			if(firstrow!=null&&maxrow!=null){
				sqlS.append(" limit "+firstrow+","+maxrow+"");
			}
			logger.info("findAllNews2Entity excute dql: " + sqlS.toString());
			ArrayList conList = this.queryALLResultSet(sqlS.toString());
			newsList=new ArrayList<NewsVo>();
			NewsVo newsVo=null;
			SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(conList.size()>0)
			{
				for(int i=0;i<conList.size();i++)
				{
					HashMap tmp = (HashMap)conList.get(i);
					newsVo=new NewsVo();
					newsVo.setContentId((String)tmp.get("contentid"));
					newsVo.setCid(Integer.parseInt((String)tmp.get("cid")));
					newsVo.setContentName((String)tmp.get("contenttitle"));
					newsVo.setContentStatus((String)tmp.get("content_status"));
					newsVo.setTestStatus((String)tmp.get("test_status"));
					newsVo.setUserId((String)tmp.get("user_id"));
					newsVo.setLastupdatetime(fmt_temp.parse((String)tmp.get("updatetime")));
					newsVo.setCause((String)tmp.get("cause"));
					newsVo.setWeburl((String)tmp.get("weburl"));
					sql="select sum(nr.size) sizenr from news_contenttitle nc,news_resources nr,news_contenresource ncr"
						+" where nc.cid="+newsVo.getCid()+" and nc.cid=ncr.cid and nr.rid=ncr.rid group by ncr.cid";
					String sizestr = queryOne(sql);
					int size = 0;
					if(sizestr != null && !"".equals(sizestr))
					{
						size = Integer.parseInt(sizestr);
						newsVo.setAttachSize(size/1024+" K");
					}
					newsList.add(newsVo);
				}
			}
			
		} catch (Exception e) {
			logger.error("findAllNews2Entity fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return newsList;
	}
	
	public NewsVo getNews2ByCOntentid(String contentid)
	{
		NewsVo tmp = null;
		this.sql = "SELECT n FROM NewsContenttitle n where n.contentid=:contentid";
		try {
			Query query = em.createQuery(sql);
			query.setParameter("contentid", contentid.trim());
			NewsContenttitle s = (NewsContenttitle) query.getSingleResult();
			if(s != null)
			{
				tmp = new NewsVo();
				tmp.setCid(s.getCid());
				tmp.setContentId(s.getContentid());
				tmp.setContentName(s.getContenttitle());
				tmp.setContenticon(s.getContenticon()+"");
				tmp.setContentInfo(s.getContenttext());
				tmp.setPubCompany(s.getContentsource());
				tmp.setContentType(s.getNewstype());
				tmp.setContentHtml(s.getContenthtml());
				tmp.setContentSummary(s.getContentsummary());
				tmp.setAllowScoring(s.getAllowScoring());
				tmp.setAllowComments(s.getAllowComments());
				tmp.setLastupdatetime(s.getUpdatetime());
				tmp.setWeburl(s.getWeburl());
			}
		} catch (Exception e) {
			log.error(" getNewsByCOntentid fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return tmp;
	}
	
	public String addNews2(NewsVo news,List<NewsResources> nrlist)  throws Exception{
		String cid=null;
			sql = "insert into t_contents (contentid,user_id,content_name,content_summary,content_type,content_updateddate,content_status," +
					"test_status,pub_company) values ('"+news.getContentId()+"','"+news.getUserId()+"','"+news.getContentName()+"','"+
					news.getContentSummary()+"','11',now(),'"+news.getContentStatus()+"','"+news.getTestStatus()
					+"','"+news.getPubCompany()+"')";
			em.createNativeQuery(sql).executeUpdate();
			
			String contenticon = SysProperty.getPrep("sysiconid_title");
			if(contenticon == null || contenticon.equals(""))
	        	contenticon = "1";
			NewsContenttitle contenttitle=new NewsContenttitle();
			contenttitle.setContentid(news.getContentId());
			contenttitle.setContenttitle(news.getContentName());
			contenttitle.setContenticon(Integer.parseInt(contenticon));
			contenttitle.setContentsummary(news.getContentSummary());
			contenttitle.setContentsource(news.getPubCompany());
			contenttitle.setNewstype(news.getContentType());
			contenttitle.setAllowScoring(news.getAllowScoring());
			contenttitle.setAllowComments(news.getAllowComments());
			//contenttitle.setWeburl(news.getWeburl());
			em.persist(contenttitle);
			cid=contenttitle.getCid()+"";
			contenttitle.setWeburl(news.getWeburl().replace("cid", cid));
			em.merge(contenttitle);
			em.flush();
			String temp_sql = "insert into t_channel_contents(channel_id,contentid) values (";
			String newChSql="insert into news_extends_channel_title(channleid,cid,contentstatus,istest,isnew)VALUES(";
			String[] chIds = news.getChannelId().split(",");
			int isNeedTest = 0;
			String needtest = SysProperty.getPrep("news-needtest");
			if(needtest!=null && needtest.equals("false"))
				isNeedTest = 1;
			//栏目和内容的关系
			int channleid=0;
			for (int i = 0; i < chIds.length; i++) {
				sql=temp_sql + chIds[i] + ",'" + news.getContentId() + "')";
				em.createNativeQuery(sql).executeUpdate();
				
				sql="select channleid from news_extends_channel where channel_id='"+chIds[i].substring(1, chIds[i].length()-1)+"'";
				channleid=this.getOneInt();
				
				sql=newChSql+channleid+","+cid+",0,"+isNeedTest+",1)";
				em.createNativeQuery(sql).executeUpdate();
			}
			//新闻图片和内容的关系
			for(NewsResources newsResources:nrlist){
					sql = "insert into news_resources (name,resourcetype,url,size,rformat,spcode,newformat,fullpath) values ('"+newsResources.getName()+"',"+
				newsResources.getResourcetype()+",'"+newsResources.getUrl()+"',"+newsResources.getSize()+",'"+newsResources.getRformat()+"'," +
					"'"+newsResources.getSpcode()+"','"+newsResources.getNewformat()+"','"+newsResources.getFullpath()+"')";
	        	em.createNativeQuery(sql).executeUpdate();
					sql = "insert into news_contenresource (rid,cid) values ((select LAST_INSERT_ID()),"+cid+")";
				em.createNativeQuery(sql).executeUpdate();
			}
			
			//处理新闻图片和更新新闻缩略图
			sql = "select nr.rid,nr.fullpath from news_resources nr,news_contenresource ncr,news_contenttitle nc" +
			" where nr.resourcetype=1 and nr.rid=ncr.rid and ncr.cid=nc.cid and nc.contentid='"+news.getContentId()+"' order by rid";
			Integer rid = null;
			String resfilename="";
			String previewimgflag = SysProperty.getPrep("news_previewimgflag");
			List<Object[]>lll =  em.createNativeQuery(sql).getResultList();
			if(lll.size()>0){
				rid=(Integer)lll.get(0)[0];
				resfilename=(String)lll.get(0)[1];
				
				String imageSizeStr = SysProperty.getPrep("news_imagesize");
				String imageFormat = SysProperty.getPrep("news_imageformat");
				String[] imageSizeAry = null;
				String[] imageFormatAry = null;
				if(imageSizeStr!=null && !imageSizeStr.equals(""))
					imageSizeAry = imageSizeStr.split(",");
				if(imageFormat == null || imageFormat.equals(""))
					imageFormat = "jpg";
				if(imageFormat != null && imageFormat.contains(","))
					imageFormatAry = imageFormat.split(",");
				HashMap<String,String> tmpMap = null; 
				ImageScalee ims = new ImageScalee();
				log.info(" -=-=Will be scale image file-=-= " +resfilename);
				if(previewimgflag != null && "1".equals(previewimgflag))
				{
					//处理新闻缩略图
					String fullpath = resfilename;
					String imageSizeScaleStr = SysProperty.getPrep("news_imagesizescale");
		        	String imageFormatScaleStr = SysProperty.getPrep("news_imageformatscale");
		        	if(imageFormatScaleStr == null || imageFormatScaleStr.equals(""))
		        		imageFormatScaleStr = "png";
					String[] imageSizeScaleAry = imageSizeScaleStr.split(","); 
					String[] imageFormatScaleAry = imageFormatScaleStr.split(","); 
					if(imageSizeScaleAry != null&&imageSizeScaleAry.length>0)
					{
						for(String imageSizeScale:imageSizeScaleAry)
						{
							String screenWidHei = imageSizeScale.split("@")[0];
							String picWidHei = imageSizeScale.split("@")[1];
							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
							int width = Integer.parseInt(picWidHei.split("x")[0]);
							int height = Integer.parseInt(picWidHei.split("x")[1]);
							if(imageFormatScaleAry!=null && imageFormatScaleAry.length>0)
								for(String imageFormatScale:imageFormatScaleAry)
									ims.compressPicsScale(fullpath, width, height, imageFormatScale, screenWidth, screenHeight);
						}
					}
					String scaleFullPath = fullpath.replace(".", "-p.");
					sql = "delete from news_resources where name="+rid+"";
					em.createNativeQuery(sql).executeUpdate();
					sql = "insert into news_resources (name,newformat,fullpath) values("+rid+",'"+imageFormatScaleStr+"','"+scaleFullPath+"')";
					em.createNativeQuery(sql).executeUpdate();
				}
				for(int i=0;i<lll.size();i++)
				{
					resfilename=(String)lll.get(i)[1];
					//处理新闻图片
					if(!"".equals(resfilename) && imageSizeAry != null)
					{
						for(String imageSize : imageSizeAry)
						{
							String screenWidHei = imageSize.split("@")[0];
							String picWidHei = imageSize.split("@")[1];
							int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
							int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
							int width = Integer.parseInt(picWidHei.split("x")[0]);
							int height = Integer.parseInt(picWidHei.split("x")[1]);
							if(imageFormatAry != null)
								for(String imageFormatStr : imageFormatAry)
									ims.compressPics(resfilename, width, height, imageFormatStr,screenWidth,screenHeight);
							else
								ims.compressPics(resfilename, width, height, imageFormat,screenWidth,screenHeight);
						}
					}
				}
			
			}
			if(rid!=null){
				sql="select n.rid from news_resources n where n.name="+rid;
				int iconrid = getOneInt();
				if(iconrid>0){
					sql = "update news_contenttitle set contenticon="+iconrid+" where contentid='"+news.getContentId()+"'";
					em.createNativeQuery(sql).executeUpdate();
				}
	        }
		
		return cid;
	}
	
	public List<NewsResources> findResourceByNews2(Integer cid)
	{
		List<NewsResources> ll=new ArrayList<NewsResources>();
		sql = "SELECT nr FROM NewsResources nr,NewsContentResource ncr where ncr.rid=nr.rid and resourcetype=1 and ncr.cid="+cid+"";
		try {
			ll=em.createQuery(sql).getResultList();
		} catch (Exception e) {
			log.error(" findResourceByNews fail !!!" +e.getMessage());
			e.printStackTrace();
		}
		return ll;
	}
	
	public ArrayList<DataMap> findAllLastChannel2(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select   ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
				",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +
				"  from t_channels ch WHERE 1=1 " +
				//will open
				" and (channel_type='"+BookConfig.channel_type_iphonewebview2+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select   ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date" +
					",ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +
					"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
					" and (channel_type='"+BookConfig.channel_type_iphonewebview2+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			findSql = "select distinct   ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered" +
					" ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +
					"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
				" and (channel_type='"+BookConfig.channel_type_iphonewebview2+"' or channel_type='"+BookConfig.channel_type_hdnews+"') " + 
	    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
	    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public int findAllTemplatefileCount(NewsTemplate template) {	
		sql="select count(id) from NewsTemplate where 1=1 ";
		if(template!=null){
			if(template.getTemplatename()!=null&&template.getTemplatename().toString().trim().length() > 0){
				sql+=" and templatename like '%"+template.getTemplatename().toString().trim()+"%'";
			}
		}
		int r=0;
		List<Object> s=em.createQuery(sql).getResultList();
		if(s.size()!=0 && s.get(0)!=null)r=Integer.valueOf(s.get(0).toString());
		return r;
	}
	
	@SuppressWarnings("unchecked")
	public List<NewsTemplate> findAllTemplatefileList(DataMap dataMap,
			Integer firstrow, Integer maxrow) {
		NewsTemplate template=(NewsTemplate) dataMap.get("template");
		JsonPage jpage=(JsonPage) dataMap.get("jpage");
		sql = "SELECT n FROM NewsTemplate n where 1=1 ";
		if(template!=null){
			if(template.getTemplatename()!=null&&template.getTemplatename().toString().trim().length() > 0){
				sql+=" and templatename like '%"+template.getTemplatename().toString().trim()+"%'";
			}
		}
		if(jpage!=null){
			if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
				sql+=" order by "+jpage.getSidx()+" "+jpage.getSord()+"";
			}
		}
		System.out.println("-------------"+sql);
		Query query = em.createQuery(sql);
		if(firstrow!=null&&maxrow!=null){
			query.setFirstResult(firstrow);
			query.setMaxResults(maxrow);
		}
		return query.getResultList();
	}

	
	public boolean deleteTemplatefile(Integer id) {
		sql="delete from news_templatefield where templateid="+id+"";
		em.createNativeQuery(sql).executeUpdate();
		sql="delete from news_templatefile where templateid="+id+"";
		em.createNativeQuery(sql).executeUpdate();
		sql="delete from news_template where id="+id+"";
		em.createNativeQuery(sql).executeUpdate();
		return true;
	}
	
	public boolean addTemplatefile(NewsTemplate template,List<NewsTemplatefile> templatefileList,
			List<NewsTemplatefield> templatefieldList) {
		em.persist(template);
		for(NewsTemplatefield templatefield:templatefieldList){
			templatefield.setTemplate(template);
			em.persist(templatefield);
		}
		for(NewsTemplatefile templatefile:templatefileList){
			templatefile.setTemplate(template);
			em.persist(templatefile);
		}
		return true;
	}
	
	public boolean updateTemplatefileById(NewsTemplate template,List<NewsTemplatefile> templatefileList,
			List<NewsTemplatefield> templatefieldList) {
		sql="delete from NewsTemplatefield where templateid=:templateid";
		em.createQuery(sql).setParameter("templateid", template.getId()).executeUpdate();
		sql="delete from NewsTemplatefile where templateid=:templateid";
		em.createQuery(sql).setParameter("templateid", template.getId()).executeUpdate();
		
		em.merge(template);
		for(NewsTemplatefield templatefield:templatefieldList){
			templatefield.setTemplate(template);
			em.persist(templatefield);
		}
		for(NewsTemplatefile templatefile:templatefileList){
			templatefile.setTemplate(template);
			em.persist(templatefile);
		}
		return true;
	}
	
	public List<NewsTemplatefile> findTemplatefileByfileid(Integer templateid) {
		String hql = "SELECT n FROM NewsTemplatefile n where n.template.id="+templateid+"";
		return em.createQuery(hql).getResultList();
		
	}
	public List<NewsTemplatefield> findTemplatefieldByfileid(Integer templateid) {
		String hql = "SELECT n FROM NewsTemplatefield n where n.template.id="+templateid+"";
		return em.createQuery(hql).getResultList();
		
	}
	
	public void updateContenttext(String str, String cid) {
		NewsContenttitle contenttitle=(NewsContenttitle) get(NewsContenttitle.class, Integer.valueOf(cid));
		contenttitle.setContenttext(str);
		em.merge(contenttitle);
	}
	
	/*
	 * 按照数据库尺寸配置尺寸生成base64 html
	 */
	public String generateNewsHtml(List<NewsTemplatefile> templatefileList,Map<String, NewsTemplatefieldVo> fieldMap,NewsVo news) {
		String str="";
		String templatepath = "";
		String uploadpath = SysProperty.getPrep("uploadpath");
		for(NewsTemplatefile tf:templatefileList){
			templatepath=uploadpath+tf.getFilepath();
			//根据模板生成页面
			String htmlFile=uploadpath+UploadRule.genFilePath(1)+news.getCid();
			if(tf.getFtype()==2){
				htmlFile+="_ipad.html";
			}else if(tf.getFtype()==3){
				htmlFile+="_k16.html";
			}else{
				htmlFile+=".html";
			}
			if(tf.getFtype()==1){
				str=newsJspToHtmlFile(templatepath,htmlFile,tf.getFtype(),fieldMap,news);
			}else{
				newsJspToHtmlFile(templatepath,htmlFile,tf.getFtype(),fieldMap,news);
			}
		}
		return str;
	}
	/**
	 * 根据本地模板生成静态页面
	 * 
	 * @param JspFile
	 *            jsp路经
	 * @param HtmlFile
	 *            html路经
	 * @return
	 */
	public String newsJspToHtmlFile(String templatepath,String htmlFile,Integer ftype,Map<String,NewsTemplatefieldVo> fieldMap,NewsVo news) {
		String str = "";
		try {
			String tempStr = "";
			FileInputStream is = new FileInputStream(templatepath);// 读取模块文件
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
			while ((tempStr = br.readLine()) != null)
				str = str + tempStr;
			is.close();
			
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		try {
			// 替换掉模块中相应的地方
			Set<String> key = fieldMap.keySet();
			for (Iterator<String> it = key.iterator(); it.hasNext();) {
			   String s = it.next();
			   if(fieldMap.get(s).getTemplatefield().getTtype()==2){//2，文本域
				   str = str.replaceAll(s, replaceHtmlcss(fieldMap.get(s).getFieldvalue()));//处理内容中html标签属性(width,height)
			   }else  if(fieldMap.get(s).getTemplatefield().getTtype()==3||fieldMap.get(s).getTemplatefield().getTtype()==4){//3，图片
				   if(ftype==2){//ipad
					   str = str.replaceAll(s, fieldMap.get(s).getIpadtaghtm());
				   }else if(ftype==3){//k16
					   str = str.replaceAll(s, fieldMap.get(s).getK16taghtm());
				   }else{//iphone
					   str = str.replaceAll(s, fieldMap.get(s).getIphonetaghtm());
				   }
			   }else{//1，文本框
				   str = str.replaceAll(s, fieldMap.get(s).getFieldvalue());
			   }
			}
			str = str.replaceAll("###title###", news.getContentName());
			str = str.replaceAll("###source###", news.getPubCompany());
			str = str.replaceAll("###time###", (new java.text.SimpleDateFormat("yyyy年MM月dd日 ")).format(new Date()));
			String serverurl = SysProperty.getPrep("sysnodeurl_b").replaceAll("action/server.do", "");
			str = str.replaceAll("###serverurl###", serverurl);
			str = str.replaceAll("###cid###", news.getCid().toString());
			//html 根据模板生成一份格式化的*.html文件
			File f = new File(htmlFile);
			if(!f.getParentFile().exists()){
				f.getParentFile().mkdirs();
			}
			BufferedWriter o = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"utf-8"));
			o.write(str);
			o.close();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return str;
	}
	
	//处理html标签属性(width,height)
	private String replaceHtmlcss(String newsHtml) {
		if(newsHtml.contains("height=") || newsHtml.contains("HEIGHT=") || newsHtml.contains("width=") || newsHtml.contains("WIDTH="))
		{
			newsHtml = newsHtml.replaceAll("height=['\"].*?['\"]", "");
			newsHtml = newsHtml.replaceAll("HEIGHT=['\"].*?['\"]", "");
			newsHtml = newsHtml.replaceAll("width=['\"].*?['\"]", "");
			newsHtml = newsHtml.replaceAll("WIDTH=['\"].*?['\"]", "");
		}
		Pattern pattern = Pattern.compile("(style)=(\\s*(\"|'|))(.*?)(\\s*\"|'\\s*)");
		Matcher matcher = pattern.matcher(newsHtml);
		String tmp = "";
		String tmp1 = "";
		while(matcher.find()) {
			tmp = matcher.group(4);
			if(newsHtml.contains("height:") || newsHtml.contains("HEIGHT:") || newsHtml.contains("width:") || newsHtml.contains("WIDTH:")){
				tmp1 = tmp.replaceAll("height", "aaa");
				tmp1 = tmp1.replaceAll("HEIGHT", "aaa");
				tmp1 = tmp1.replaceAll("width", "aaa");
				tmp1 = tmp1.replaceAll("WIDTH", "aaa");
				newsHtml = newsHtml.replace(tmp, tmp1);
			}
		}
		
		//parse <a><img>
		String tmpaimg = "";
		String oldstr = "";
		Pattern paimg = Pattern.compile("<a.*?href=(\"|').*?(\"|')><img.*?></a>");
		Matcher maimg = paimg.matcher(newsHtml);
		Pattern pa = Pattern.compile("<a.*?href=(\"|').*?(\"|')>");
		Matcher ma = null;
		if(newsHtml != null && newsHtml.length()>0)
		{
			while (maimg.find())
			{
				tmpaimg = maimg.group();
				oldstr = tmpaimg;
				ma = pa.matcher(tmpaimg);
				if(ma.find())
				{
					String tmpa = ma.group();
					tmpaimg = tmpaimg.replaceAll(tmpa, "");
					tmpaimg = tmpaimg.replaceAll("</a>", "");
				}
				newsHtml = newsHtml.replace(oldstr, tmpaimg);
		    }
		}
		return newsHtml;
	}
	
	/*==============================================================*/
	/* Webview内容管理End                                         
	/*==============================================================*/
	
	/*==============================================================*/
	/* iphone推送消息Start                                          
	/*==============================================================*/
	/**
	 * 获得所有资讯内容、Webview内容总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public Integer findAllNews3EntityCount(DataMap hashMap){
		NewsVo news=(NewsVo) hashMap.get("news");
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		Integer iCount = 0; 
		try {
		
			StringBuffer sqlS =new StringBuffer("select count(nc.cid) from t_contents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			sqlS.append(" and (nc.newstype = 'news' or nc.newstype='iphonewebview' or nc.newstype='iphonewebview2') ");
			sqlS.append(" and tc.content_status='pass' and tc.test_status='1' ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%"+news.getContentName().toString().trim() + "%'");
				}
			}
			logger.info("findAllNews3EntityCount excute sql: " + sqlS.toString());
			sql=sqlS.toString();
				iCount=this.getOneInt();
		} catch (Exception e) {
			logger.error("findAllNews3EntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return iCount;
	}
	
	/**
	 * 获得所有资讯内容、Webview内容信息
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsVo>
	 */
	public List<NewsVo> findAllNews3Entity(DataMap hashMap, Integer firstrow,Integer maxrow){
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		NewsVo news=(NewsVo) hashMap.get("news");
		List<NewsVo> newsList = null; 
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		try {
	
			StringBuffer sqlS =new StringBuffer("select tc.contentid,nc.cid,nc.contenttitle,tc.content_status,test_status,tc.user_id," +
			"nc.updatetime,tc.cause,nc.weburl from t_contents tc,news_contenttitle nc ");
			if(news!=null && news.getChannelId()!=null&& news.getChannelId().toString().trim().length() > 0) {
				sqlS.append(",news_extends_channel nec,news_extends_channel_title nect ");
				sqlS.append(" where nec.channel_id='"+news.getChannelId()+"' and nec.channleid=nect.channleid and nc.cid=nect.cid ");
				sqlS.append(" and nc.contentid=tc.contentid");
			}
			else
				sqlS.append(" where nc.contentid=tc.contentid ");
			sqlS.append(" and (nc.newstype = 'news' or nc.newstype='iphonewebview' or nc.newstype='iphonewebview2') ");
			sqlS.append(" and tc.content_status='pass' and tc.test_status='1' ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%" + news.getContentName().toString().trim() + "%'");
				}
			}
			
			if(jpage!=null){
				if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
					sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord()+"");
				}
			}
			if(firstrow!=null&&maxrow!=null){
				sqlS.append(" limit "+firstrow+","+maxrow+"");
			}
			logger.info("findAllNews3Entity excute dql: " + sqlS.toString());
			ArrayList conList = this.queryALLResultSet(sqlS.toString());
			newsList=new ArrayList<NewsVo>();
			NewsVo newsVo=null;
			SimpleDateFormat fmt_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(conList.size()>0)
			{
				for(int i=0;i<conList.size();i++)
				{
					HashMap tmp = (HashMap)conList.get(i);
					newsVo=new NewsVo();
					newsVo.setContentId((String)tmp.get("contentid"));
					newsVo.setCid(Integer.parseInt((String)tmp.get("cid")));
					newsVo.setContentName((String)tmp.get("contenttitle"));
					newsVo.setContentStatus((String)tmp.get("content_status"));
					newsVo.setTestStatus((String)tmp.get("test_status"));
					newsVo.setUserId((String)tmp.get("user_id"));
					newsVo.setLastupdatetime(fmt_temp.parse((String)tmp.get("updatetime")));
					newsVo.setCause((String)tmp.get("cause"));
					newsVo.setWeburl((String)tmp.get("weburl"));
					newsList.add(newsVo);
				}
			}
			
		} catch (Exception e) {
			logger.error("findAllNews3Entity fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return newsList;
	}
	
	public ArrayList<DataMap> findAllLastChannel3(DataMap hashMap) {
		Object roleId = hashMap.get("role_id");
		Object userId = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		//root
		String findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch WHERE 1=1 " +
				//will open
				" and (channel_type='"+BookConfig.channel_type_iphonewebview2+"' or channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
				" AND (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"') ";
		//normal user
		if(roleId != null && !roleId.equals(""))
		{
			findSql = "select  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
					" and (channel_type='"+BookConfig.channel_type_iphonewebview2+"' or channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
		    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
		    		" and uc.employee_id=(SELECT employee_id FROM t_user where user_id='" + userId + "')";
		}else if(userids!=null){
			findSql = "select distinct  ch.channel_id  ,ch.service_code,ch.channel_name,ch.channel_comment ,ch.function_name,ch.STATUS ,ch.ordered ,ch.created_date,ch.previous_id ,ch.primal_id ,ch.LEVEL ,ch.channel_type  ,ch.channel_hot_topics ,ch.channel_classifying_label" +"  from t_channels ch,t_user_channels uc WHERE ch.channel_id=uc.channel_id " +
				" and (channel_type='"+BookConfig.channel_type_iphonewebview2+"' or channel_type='"+BookConfig.channel_type_news+"' or channel_type='"+BookConfig.channel_type_iphonewebview+"' or channel_type='"+BookConfig.channel_type_scrollbar+"') " + 
	    		" and (function_name='"+BookConfig.channel_last+"' OR function_name='"+BookConfig.channel_song+"')  " +
	    		" and uc.employee_id in (SELECT employee_id FROM t_user where user_id in (" + userids + "))";
		}
		try {
			return this.queryALLResultSet(findSql.toString());
		} catch (Exception e) {
			logger.error(" findAllLastChannel fail !!!" +e.getMessage());
			return null;
		}
	}
	
	public boolean insertPushMsg(int cid) {

		NewsVo news = null;
		this.sql = "SELECT n.cid,n.contenttitle FROM NewsContenttitle n where n.cid=:cid";
		Query query = em.createQuery(sql);
		query.setParameter("cid", cid);
		List<Object[]> ll=query.getResultList();
		if(ll.size()>0)
		{
			news = new NewsVo();
			news.setCid((Integer)ll.get(0)[0]);
			news.setContentName((String)ll.get(0)[1]);
		}
		
		sql="select clientid,token from news_iphonevalidclient";
		query=em.createNativeQuery(sql);
		int clientid=0;
		String token="";
		List<Object[]> lll= query.getResultList();
		if(lll.size()>0){
			for(int i=0;i<lll.size();i++){
				clientid=(Integer)lll.get(i)[0];
				token=(String)lll.get(i)[1];
				sql="insert into news_iphonewillsendmsg(clientid,token,msgid,msgtype,msg,msgtipe) values(?,?,?,?,?,?)";
				query=em.createNativeQuery(sql);
				query.setParameter(1, clientid);
				query.setParameter(2, token);
				query.setParameter(3, news.getCid());
				query.setParameter(4, 99);
				query.setParameter(5, news.getContentName());
				query.setParameter(6, "");
				query.executeUpdate();
			}
		}
		return true;
	}
	/*==============================================================*/
	/* iphone推送消息End                                          
	/*==============================================================*/
	
	/*==============================================================*/
	/* 杂志问卷调查管理Start
	/*==============================================================*/
	/**
	 * 杂志问卷内容总记录数
	 * @param hashMap
	 * @return Integer
	 */
	public Integer findAllNews4EntityCount(DataMap hashMap){
		NewsVo news=(NewsVo) hashMap.get("news");
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		Integer iCount = 0; 
		try {
			
			StringBuffer sqlS =new StringBuffer("select count(distinct nc.cid) from news_contenttitle nc,news_news_question nnq,t_contents tc where nnq.cid=nc.cid and nc.contentid=tc.contentid ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%" + news.getContentName().toString().trim() + "%'");
				}
			}
			logger.info("findAllNews4EntityCount excute sql: " + sqlS.toString());
			sql=sqlS.toString();
				iCount=this.getOneInt();
		} catch (Exception e) {
			logger.error("findAllNews4EntityCount fail !!!" + e.getMessage());
			e.printStackTrace();
		}
		return iCount;
	}
	
	/**
	 * 获得所有杂志问卷内容信息
	 * @param hashMap
	 * @param firstrow
	 * @param maxrow
	 * @return List<NewsVo>
	 */
	public List<NewsVo> findAllNews4Entity(DataMap hashMap, Integer firstrow,Integer maxrow){
		NewsVo news=(NewsVo) hashMap.get("news");
		JsonPage jpage=(JsonPage) hashMap.get("jpage");
		List<NewsVo> newsList = null; 
		Object s_role_id = hashMap.get("role_id");
		Object s_user_id = hashMap.get("user_id");
		String userids = (String)hashMap.get("userids");
		try {
			
			StringBuffer sqlS =new StringBuffer("select distinct nc.cid,nc.contentid,nc.contenttitle from news_contenttitle nc,news_news_question nnq,t_contents tc where nnq.cid=nc.cid and nc.contentid=tc.contentid ");
			if(s_role_id!=null&&!"".equals(s_role_id)) {
				sqlS.append(" and tc.user_id = '"+ s_user_id +"'");
			}else if(userids!=null){
				sqlS.append(" and tc.user_id in ("+ userids +")");
			}
			if(news!=null){
				if(news.getContentName()!=null&& news.getContentName().toString().trim().length() > 0){
					sqlS.append(" AND nc.contenttitle like '%" + news.getContentName().toString().trim() + "%'");
				}
			}
			if(jpage!=null){
				if(jpage.getSidx()!=null&&!"".equals(jpage.getSidx())){
					sqlS.append(" order by "+jpage.getSidx()+" "+jpage.getSord()+"");
				}
			}
			if(firstrow!=null&&maxrow!=null){
				sqlS.append(" limit "+firstrow+","+maxrow+"");
			}
			logger.info("findAllNews4Entity excute dql: " + sqlS.toString());
			ArrayList conList = this.queryALLResultSet(sqlS.toString());
			newsList=new ArrayList<NewsVo>();
			NewsVo newsVo=null;
			if(conList.size()>0)
			{
				for(int i=0;i<conList.size();i++)
				{
					HashMap tmp = (HashMap)conList.get(i);
					newsVo=new NewsVo();
					newsVo.setContentId((String)tmp.get("contentid"));
					newsVo.setCid(Integer.parseInt((String)tmp.get("cid")));
					newsVo.setContentName((String)tmp.get("contenttitle"));
					newsList.add(newsVo);
				}
			}
		
		} catch (Exception e) {
			logger.error("findAllNews4Entity fail !!!" + e.getMessage());
			e.printStackTrace();
		} 
		return newsList;
	}
	/*==============================================================*/
	/* 杂志问卷调查管理End
	/*==============================================================*/
}